package com.diycode.controller;

import com.diycode.entity.Trains;
import com.diycode.service.TrainsService;
import com.diycode.utils.MapControl;
import com.github.pagehelper.PageInfo;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author diycode
 */
@Controller
@RequestMapping("/trains")
public class TrainsController {

    private static final String LIST = "trains/list";
    private static final String ADD = "trains/add";

    @Resource
    private TrainsService trainsService;

    //跳转列表页面
    @GetMapping("/list")
    public String list() {
        return LIST;
    }

    //查询
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> query(@RequestBody Trains trains) {
        PageInfo<Trains> pageInfo=trainsService.query(trains);
         return MapControl.getInstance().success().page( pageInfo.getList(),(int)pageInfo.getTotal()).getMap();
     }

    //根据id查询，跳转修改页面
    @GetMapping(value = {"/detail","/detail/{id}"})
    public String detail(@PathVariable(value = "id",required = false) Integer id, ModelMap modelMap) {
       if(id!=null) {
           //查询出要修改的信息
           Trains trains = trainsService.detail(id);
           //将查询出来的数据存储到request域，实现表单回显
           modelMap.addAttribute("trains", trains);
       }
       return ADD;
    }

    @PostMapping("/saveOrUpdate")
    @ResponseBody
    public Map<String,Object> saveOrUpdate(@RequestBody Trains trains){
        Boolean result=trainsService.saveOrUpdate(trains);
        if (result) {
            return MapControl.getInstance().success().getMap();
        }
        return MapControl.getInstance().error().getMap();
    }

    //根据id删除
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") Integer id) {
        int result = trainsService.delete(id);
        if (result <= 0) {
        return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

     //批量删除
     @PostMapping("/delete")
     @ResponseBody
     public Map<String, Object> delete(String ids) {
         int result = trainsService.delete(ids);
         if (result <= 0) {
         return MapControl.getInstance().error().getMap();
         }
         return MapControl.getInstance().success().getMap();
     }

}
